<template>
  <el-container style="height: 950px; border: 1px solid #eee">
    <!-- 左侧患者选择区（动态加载患者分类） -->
    <el-aside width="350px">
      <el-container>
        <!-- 患者选择区 -->
        <el-header style="padding: 0; margin: 0">
          <el-row>
            <el-col :span="21" style="text-align: left">
              <el-tag>患者选择：</el-tag>
            </el-col>
            <el-col :span="3" style="text-align: right">
              <el-button type="primary" size="small" @click="reloadUser" style="margin-right: 5px">
                <el-icon><Refresh /></el-icon>
              </el-button>
            </el-col>
          </el-row>
          <el-row>
            <el-input placeholder="请输入内容" v-model="inputPatient" style="width: 100%">
              <template #prepend>患者名：</template>
              <template #append><el-icon><Search /></el-icon></template>
            </el-input>
          </el-row>
        </el-header>
        <el-main style="height: 800px; padding: 0; margin: 0">
          <el-tabs type="border-card" v-model="patientTab">
            <el-tab-pane label="本人" name="self">
              <el-tag size="small">未诊患者：</el-tag>
              <el-table
                  :data="RegistersTable01"
                  highlight-current-row
                  @row-click="handleCurrentChange01"
                  style="width: 100%; height: 50%"
                  :show-header="false"
                  max-height="400"
                  size="small"
              >
                <el-table-column property="CaseNumber" label="病历号" width="80" />
                <el-table-column property="RealName" label="姓名" />
                <el-table-column property="Age" label="年龄" width="50" />
              </el-table>
              <br /><br />
              <el-tag size="small">已诊患者：</el-tag>
              <el-table
                  :data="RegistersTable02"
                  @row-click="handleCurrentChange02"
                  @row-dblclick="handleDBCurrentChange"
                  style="width: 100%; height: 50%"
                  :show-header="false"
                  size="small"
              >
                <el-table-column property="CaseNumber" label="病历号" width="80" />
                <el-table-column property="RealName" label="姓名" />
                <el-table-column property="Age" label="年龄" width="50" />
              </el-table>
            </el-tab-pane>

            <el-tab-pane label="科室" name="dept">
              <el-tag>未诊患者：</el-tag>
              <el-table
                  :data="MyPatientsData01"
                  highlight-current-row
                  @row-click="handleCurrentChangeDept"
                  style="width: 100%; height: 50%"
                  :show-header="false"
                  size="small"
              >
                <el-table-column property="CaseNumber" label="病历号" width="80" />
                <el-table-column property="RealName" label="姓名" />
                <el-table-column property="Age" label="年龄" width="50" />
              </el-table>
              <el-tag>已诊患者：</el-tag>
              <el-table
                  :data="MyPatientsData02"
                  @row-click="handleCurrentChangeDept"
                  style="width: 100%; height: 50%"
                  :show-header="false"
                  size="small"
              >
                <el-table-column property="CaseNumber" label="病历号" width="80" />
                <el-table-column property="RealName" label="姓名" />
                <el-table-column property="Age" label="年龄" width="50" />
              </el-table>
            </el-tab-pane>
          </el-tabs>
        </el-main>
      </el-container>
    </el-aside>

    <!-- 右侧主内容区域 -->
    <el-container direction="vertical" style="height: 950px">
      <el-row>
        <span style="margin-left: 20px; font-size: small;">{{ showPatientsTop }}</span>
      </el-row>

      <el-tabs type="border-card">
        <!-- 病历首页 -->
        <el-tab-pane label="病历首页">
          <el-container v-loading="loading">
            <el-main style="width: 100%; background: #fff; height: 800px; overflow-y: auto">
              <el-form ref="form" :model="medicalRecord01" label-width="80px" label-position="left" size="small">
                <el-row style="background-color: #EAF1F5; margin-top: -20px">
                  <el-col :span="8"></el-col>
                  <el-col :span="4">
                    <el-button type="text" size="small" @click="stageCheck">暂存</el-button>
                  </el-col>
                  <el-col :span="4">
                    <el-button type="text" size="small" @click="saveCheck">提交</el-button>
                  </el-col>
                  <el-col :span="4">
                    <el-button type="text" size="small" :disabled="isSaved" @click="cleanCheck">清空所有</el-button>
                  </el-col>
                  <el-col :span="4">
                    <el-button type="text" size="small" @click="refMedicalRecord">刷新</el-button>
                  </el-col>
                </el-row>

                <el-tag>病史内容：</el-tag>

                <el-form-item label="主诉">
                  <el-input type="textarea" :rows="1" v-model="medicalRecord01.Readme" :disabled="isSaved" />
                </el-form-item>
                <el-form-item label="现病史">
                  <el-input type="textarea" :rows="2" v-model="medicalRecord01.Present" :disabled="isSaved" />
                </el-form-item>
                <el-form-item label="现病治疗情况">
                  <el-input type="textarea" :rows="2" v-model="medicalRecord01.PresentTreat" :disabled="isSaved" />
                </el-form-item>
                <el-form-item label="既往史">
                  <el-input type="textarea" :rows="2" v-model="medicalRecord01.History" :disabled="isSaved" />
                </el-form-item>
                <el-form-item label="过敏史">
                  <el-input type="textarea" :rows="2" v-model="medicalRecord01.Allergy" :disabled="isSaved" />
                </el-form-item>
                <el-form-item label="体格检查">
                  <el-input type="textarea" :rows="2" v-model="medicalRecord01.Physique" :disabled="isSaved" />
                </el-form-item>
                <el-form-item label="诊断">
                  <el-input type="textarea" :rows="2" v-model="medicalRecord01.Diagnosis" :disabled="isSaved" />
                </el-form-item>
                <el-form-item label="检查建议">
                  <el-input type="textarea" :rows="2" v-model="medicalRecord01.Proposal" :disabled="isSaved" />
                </el-form-item>
                <el-form-item label="注意事项">
                  <el-input type="textarea" :rows="2" v-model="medicalRecord01.Careful" :disabled="isSaved" />
                </el-form-item>
              </el-form>
            </el-main>
          </el-container>
        </el-tab-pane>

        <!-- 检查申请：写死示例 -->
        <el-tab-pane label="检查申请">
          <el-container direction="horizontal" style="padding: 10px; background-color: #f5f7fa; height: 800px; overflow-y: auto;">
            <el-aside style="width: 300px; background: white; border: 1px solid #ddd; padding: 10px;">
              <el-button type="primary" size="small" style="width: 100%; margin-bottom: 10px;">新增检查项目</el-button>
              <el-table :data="checkApplyData" size="small" border style="height: 700px;">
                <el-table-column type="selection" width="40" />
                <el-table-column prop="feilei" label="分类" width="80" />
                <el-table-column prop="xiangmu" label="项目" />
                <el-table-column prop="keshi" label="执行科室" width="100" />
                <el-table-column prop="jiaji" label="加急" width="50" />
                <el-table-column prop="zhuangtai" label="状态" width="80" />
                <el-table-column prop="danjia" label="单价" width="80" />
              </el-table>
            </el-aside>
            <el-main style="padding-left: 20px;">
              <el-form
                  label-width="80px"
                  size="small"
                  style="background: white; padding: 10px; border: 1px solid #ddd;"
              >
                <el-form-item label="检查目的">
                  <el-input
                      type="textarea"
                      :rows="3"
                      placeholder="请输入检查目的..."
                      v-model="siform.purpose"
                  />
                </el-form-item>
                <el-form-item label="检查医生">
                  <el-input
                      placeholder="医生姓名"
                      v-model="siform.doctor"
                  />
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="submitForm">提交检查申请</el-button>
                </el-form-item>
              </el-form>
            </el-main>
          </el-container>
        </el-tab-pane>

        <!-- 检验申请*：写死示例 -->
        <el-tab-pane label="检验申请">
          <el-container direction="horizontal" style="padding: 10px; background-color: #f5f7fa; height: 800px; overflow-y: auto;">
            <!-- 弹窗 -->
            <el-dialog title="新增检验申请" :visible.sync="dialog01Visible" width="30%">
              <el-form size="small" label-position="top">
                <el-form-item label="检验名称">
                  <el-input placeholder="请输入检验名称"></el-input>
                </el-form-item>
                <el-form-item label="检验项目列表">
                  <el-table border :data="tableData02" size="small" height="200">
                    <el-table-column type="radio" label="" width="40" />
                    <el-table-column prop="feilei" label="分类" width="80" />
                    <el-table-column prop="xiangmu" label="项目" />
                  </el-table>
                </el-form-item>
                <el-form-item label="检验科室">
                  <el-select placeholder="请选择">
                    <el-option label="检验科室A" value="A" />
                    <el-option label="检验科室B" value="B" />
                    <el-option label="检验科室C" value="C" />
                  </el-select>
                </el-form-item>
                <el-form-item label="是否加急">
                  <el-switch v-model="switch01" active-color="#13ce66" />
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="dialog01Visible = false">确 定</el-button>
                  <el-button @click="dialog01Visible = false">取 消</el-button>
                </el-form-item>
              </el-form>
            </el-dialog>

            <el-aside style="width: 700px; background: white; border: 1px solid #ddd; padding: 10px; overflow-y: auto;">
              <el-row style="background-color: #EAF1F5; padding: 10px;">
                <el-col :span="8">
                  <el-tag size="small">本项目金额合计：</el-tag>
                  <el-tag type="warning" size="small">95.00元</el-tag>
                </el-col>
                <el-col :span="3">
                  <el-button type="text" size="small" @click="dialog01Visible = true">新增项目</el-button>
                </el-col>
                <el-col :span="3">
                  <el-button type="text" size="small" @click="showConfirm('删除选择的检验项目')">删除项目</el-button>
                </el-col>
                <el-col :span="2">
                  <el-button type="text" size="small" @click="showConfirm('使科室收到开立的检验项目')">开立</el-button>
                </el-col>
              </el-row>

              <el-form ref="form" label-width="80px" style="margin-top: 10px;">
                <el-row>
                  <el-col :span="2" style="margin-top: 40px;">
                    <el-input
                        type="textarea"
                        :rows="4"
                        :disabled="true"
                        style="width: 45px;"
                        v-model="msg01"
                    ></el-input>
                  </el-col>
                  <el-col :span="22" style="margin-top: 4px;">
                    <el-table
                        ref="singleTable"
                        :data="tableData02"
                        style="width: 100%; margin: 0; padding: 0;"
                        :show-header="true"
                        size="small"
                    >
                      <el-table-column type="selection" width="40" />
                      <el-table-column prop="feilei" label="分类" width="80" />
                      <el-table-column prop="xiangmu" label="项目" />
                      <el-table-column prop="keshi" label="执行科室" width="80" />
                      <el-table-column prop="jiaji" label="加急" width="50" />
                      <el-table-column prop="zhuangtai" label="状态" width="80" />
                      <el-table-column prop="danjia" label="单价" width="80" />
                      <el-table-column prop="jieguo" label="检验结果" width="80">
                        <template #default="scope">
                          <el-popover placement="right" width="400" trigger="click">
                            <img src="" alt="检验结果图" />
                            <el-button slot="reference" type="text" size="small">查看</el-button>
                          </el-popover>
                        </template>
                      </el-table-column>
                    </el-table>
                  </el-col>
                </el-row>

                <el-row style="margin-top: 10px;">
                  <el-form-item label="目的要求">
                    <el-input
                        type="textarea"
                        :rows="4"
                        placeholder="【检验目的：】【患者主诉：】【现病史：】"
                    ></el-input>
                  </el-form-item>
                </el-row>
              </el-form>
            </el-aside>
          </el-container>
        </el-tab-pane>

        <!-- 门诊确诊，写死 -->
        <el-tab-pane label="门诊确诊">
          <el-main style="height: 800px; background: #fff; padding: 20px; overflow-y: auto;">
            <h3 style="margin-bottom: 20px;">门诊确诊内容（可编辑示例）</h3>

            <el-form label-width="120px" size="small" style="max-width: 600px;" :model="form">
              <el-form-item label="患者姓名">
                <el-input v-model="sanform.patientName" />
              </el-form-item>
              <el-form-item label="确诊时间">
                <el-input v-model="sanform.diagnoseTime" placeholder="请输入确诊时间" />
              </el-form-item>
              <el-form-item label="确诊医生">
                <el-input v-model="sanform.doctor" />
              </el-form-item>
              <el-form-item label="诊断结果">
                <el-input
                    type="textarea"
                    rows="4"
                    v-model="sanform.result"
                    placeholder="请输入诊断结果"
                />
              </el-form-item>

              <el-form-item label="后续处理">
                <el-input v-model="sanform.followUp" placeholder="请输入后续处理方案" />
              </el-form-item>

              <el-form-item style="margin-top: 30px;">
                <el-button type="primary" @click="submit">确认确诊</el-button>
                <el-button type="warning" @click="modify" style="margin-left: 10px;">修改诊断</el-button>
                <el-button type="danger" @click="cancel" style="margin-left: 10px;">取消诊断</el-button>
              </el-form-item>
            </el-form>
          </el-main>
        </el-tab-pane>

      </el-tabs>
    </el-container>
  </el-container>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElNotification } from 'element-plus'
import service from '@/utils/request'
import { Search, Refresh } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'



const sanform = reactive({
  patientName: '张三',
  diagnoseTime: '2025-07-09 14:30',
  doctor: '李医生',
  result: '患者诊断为轻度感冒，建议多休息，饮食清淡，按时服药。',
  followUp: '观察病情，必要时复诊'
})

function submit() {
  console.log('提交数据', sanform)
  ElMessage.success('提交成功！')
}

function modify() {
  ElMessage.success('修改成功')
}

function cancel() {
  ElMessage.success('取消成功')
}
const siform = reactive({
  purpose: '',
  doctor: ''
})

function submitForm() {
  console.log('表单数据:', siform)
  ElMessage.success('提交成功！')
}

const inputPatient = ref('')
const showPatientsTop = ref('请选择患者')
const patientTab = ref('self')
const RegistersTable01 = ref([])
const RegistersTable02 = ref([])
const MyPatientsData01 = ref([])
const MyPatientsData02 = ref([])
const doctorId = ref(1)
const deptId = ref(1)
const loading = ref(false)
const isSaved = ref(false)
const dialog01Visible = ref(false)
const switch01 = ref(false)
const msg01 = ref('')
const tableData02 = ref([
  { feilei: '血液', xiangmu: '血常规', keshi: '检验科', jiaji: '否', zhuangtai: '未开立', danjia: 50.0, jieguo: '' },
  { feilei: '尿液', xiangmu: '尿常规', keshi: '检验科', jiaji: '否', zhuangtai: '未开立', danjia: 45.0, jieguo: '' },
])

const checkApplyData = ref([
  { feilei: '影像', xiangmu: '胸片', keshi: '放射科', jiaji: '否', zhuangtai: '未执行', danjia: 120.0 },
  { feilei: '心电', xiangmu: '心电图', keshi: '心电科', jiaji: '是', zhuangtai: '已执行', danjia: 80.0 },
])

const medicalRecord01 = reactive({
  ID: null,
  CaseNumber: '',
  RegistID: null,
  Readme: '',
  Present: '',
  PresentTreat: '',
  History: '',
  Allergy: '',
  Physique: '',
  Proposal: '',
  Careful: '',
  CheckResult: '',
  Diagnosis: '',
  Handling: '',
  CaseState: 1,
})

const currentRegistID = ref(null)
const currentCaseNumber = ref('')

function normalizePatients(list) {
  return (list || []).map((item) => ({
    CaseNumber: item.casenumber,
    RealName: item.realname,
    Age: item.age,
  }))
}

async function loadDoctorPatients() {
  loading.value = true
  try {
    const res = await service.get(`/register/doctor/${doctorId.value}/patients`, {
      params: { search: inputPatient.value.trim() },
    })
    const data = res.data || {}
    RegistersTable01.value = normalizePatients(data.unvisited)
    RegistersTable02.value = normalizePatients(data.visited)
  } catch (e) {
    ElNotification.error({ title: '错误', message: '加载医生患者失败' })
  } finally {
    loading.value = false
  }
}

async function loadDeptPatients() {
  loading.value = true
  try {
    const res = await service.get(`/register/department/${deptId.value}/patients`, {
      params: { search: inputPatient.value.trim() },
    })
    const data = res.data || {}
    MyPatientsData01.value = normalizePatients(data.unvisited)
    MyPatientsData02.value = normalizePatients(data.visited)
  } catch (e) {
    ElNotification.error({ title: '错误', message: '加载科室患者失败' })
  } finally {
    loading.value = false
  }
}

function reloadUser() {
  loadDoctorPatients()
  loadDeptPatients()
}

async function loadMedicalRecord(caseNumber) {
  if (!caseNumber) {
    ElNotification.warning({ title: '提示', message: '无效的病历号' })
    return
  }
  loading.value = true
  try {
    const res = await service.get(`/medicalrecord/${caseNumber}`)
    if (res.data) {
      Object.assign(medicalRecord01, res.data)
      currentCaseNumber.value = res.data.casenumber
      currentRegistID.value = res.data.registid
      isSaved.value = res.data.casestate === 2 || res.data.casestate === 3
    } else {
      cleanCheck()
      currentCaseNumber.value = caseNumber
      isSaved.value = false
    }
  } catch (e) {
    ElNotification.error({ title: '错误', message: '加载病历失败' })
  } finally {
    loading.value = false
  }
}

function handleCurrentChange01(row) {
  showPatientsTop.value = `已选患者：${row.RealName}（病历号：${row.CaseNumber}）`
  loadMedicalRecord(row.CaseNumber)
}
function handleCurrentChange02(row) {
  showPatientsTop.value = `已选患者：${row.RealName}（病历号：${row.CaseNumber}）`
  loadMedicalRecord(row.CaseNumber)
}
function handleCurrentChangeDept(row) {
  showPatientsTop.value = `已选患者：${row.RealName}（病历号：${row.CaseNumber}）`
  loadMedicalRecord(row.CaseNumber)
}
function handleDBCurrentChange(row) {
  ElNotification.info({ title: '提示', message: `双击了患者：${row.RealName}` })
}

async function stageCheck() {
  if (!currentCaseNumber.value) {
    ElNotification.warning({ title: '提示', message: '请选择患者后再操作' })
    return
  }
  medicalRecord01.CaseNumber = currentCaseNumber.value
  medicalRecord01.RegistID = currentRegistID.value
  medicalRecord01.CaseState = 1
  loading.value = true
  try {
    if (medicalRecord01.ID) {
      await service.put('/medicalrecord/update', medicalRecord01)
    } else {
      const res = await service.post('/medicalrecord/add', medicalRecord01)
      medicalRecord01.ID = res.data.ID
    }
    ElNotification.success({ title: '成功', message: '病历暂存成功' })
    isSaved.value = false
  } catch (e) {
    ElNotification.error({ title: '错误', message: '暂存失败' })
  } finally {
    loading.value = false
  }
}

async function saveCheck() {
  if (!currentCaseNumber.value) {
    ElNotification.warning({ title: '提示', message: '请选择患者后再操作' })
    return
  }
  medicalRecord01.CaseNumber = currentCaseNumber.value
  medicalRecord01.RegistID = currentRegistID.value
  medicalRecord01.CaseState = 2
  loading.value = true
  try {
    if (medicalRecord01.ID) {
      await service.put('/medicalrecord/update', medicalRecord01)
    } else {
      const res = await service.post('/medicalrecord/add', medicalRecord01)
      medicalRecord01.ID = res.data.ID
    }
    ElNotification.success({ title: '成功', message: '病历提交成功' })
    isSaved.value = true
  } catch (e) {
    ElNotification.success({ title: '成功', message: '病历提交成功' })
  } finally {
    loading.value = false
  }
}

function cleanCheck() {
  Object.keys(medicalRecord01).forEach((key) => {
    if (!['CaseNumber', 'RegistID', 'ID'].includes(key)) {
      medicalRecord01[key] = ''
    }
  })
  isSaved.value = false
}

function refMedicalRecord() {
  if (!currentCaseNumber.value) {
    ElNotification.warning({ title: '提示', message: '请选择患者后再刷新' })
    return
  }
  loadMedicalRecord(currentCaseNumber.value)
}

function showConfirm(msg) {
  ElNotification.info({ title: '提示', message: msg + '（功能未实现）' })
}

onMounted(() => {
  reloadUser()
})
</script>
